<template>
  <div>
    <van-nav-bar class="top"
      title="城市列表"
      left-arrow
      @click-left="$router.push('/home')"
    />
    
    
    <van-index-bar :index-list="indexList" class="list"> 
        <van-index-anchor index="#" >当前城市</van-index-anchor>
      <van-cell @click="changeCity($store.state.city.cityName,$store.state.city.cityCode)" > {{$store.state.city.cityName}}
      </van-cell >

      <van-index-anchor index="热门城市" />
      <van-cell v-for="item in hotList" :key="item.value" :title="item.label" @click="changeCity(item.label,item.value)" />
<!-- 字母排序 -->
      <div v-for="item in arr" :key="item">
        <van-index-anchor :index="item" />
        <van-cell :title="item.label" v-for="item in cityObj[item]" :key="item.value" @click="changeCity(item.label,item.value)" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { getList, getHot } from '@/api/house'
export default {
  name: 'City',
  async created() {
    const res = await getList()
    const data = await getHot()
    console.log(res)

    this.hotList = [...data.body]
    this.cityList = [...res.body]
     for (let i = 65; i <= 90; i++) {
        this.indexList.push(String.fromCharCode(i))
      }
        this.indexList=['#','热',...this.indexList]
       this.indexList.forEach((item) => {
          this.cityList.forEach(city =>{
            if(city.short.charAt(0).toUpperCase() === item){
              if(!this.cityObj[item]){
                this.cityObj[item]=[]
                this.arr.push(item)
              }
              this.cityObj[item].push(city)
            }
          })
      })  
      
    
  },
  data() {
    return {
      arr:[],
      cityList: [],
      hotList: null,
      cityObj:{},
      indexList:[]
    }
  },
  methods:{
    changeCity(city,code){
      this.$store.commit('city/changeCity',{city,code})
      this.$router.go(-1)
    }
  },
  computed: {
  
   
  },
}
</script>

<style scoped lang="less">
 .top{
    position: fixed;
    top:0;
    z-index: 999;
    width: 100%;
  
  }
  .list{
    margin-top: 50px;
  }
</style>
